package com.fengwan.wastesort.ui.fragment

import androidx.lifecycle.ViewModelProviders
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter

import com.fengwan.wastesort.R
import com.fengwan.wastesort.adapter.WasteSortAdapter
import com.fengwan.wastesort.adapter.WasteSortAdapter2
import com.fengwan.wastesort.model.Waste
import com.fengwan.wastesort.ui.viewModel.WasteCycleViewModel
import kotlinx.android.synthetic.main.fragment_waste_sort.*

class WasteCycleFragment : BaseWasteFragment(), BaseQuickAdapter.RequestLoadMoreListener, Observer<List<Waste>> {


    companion object {
        fun newInstance() = WasteCycleFragment()
    }

    private val adapter by lazy { WasteSortAdapter2(activity!!) }
    private val viewModel by lazy { ViewModelProviders.of(this).get(WasteCycleViewModel::class.java) }
    private var isFirst = true

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_waste_sort, container, false)
    }

    override fun initListener() {
        viewModel.cycleWastes.observe(this, this)
    }

    override fun initView(view: View) {
        recycler.layoutManager = GridLayoutManager(context, 2, RecyclerView.VERTICAL, false)
        val itemHeader = getItemHeader(R.layout.item_waste_header, recycler)
//        adapter.setHeaderView(itemHeader)
        setItemHeaderContent(
            itemHeader,
            R.color.colorWasteCycle,
            "可回收垃圾",
            R.mipmap.icon_recylable,
            "指适宜回收可循环利用的废弃物\n如废纸张、废塑料、废玻璃制品、废金属、废织物、其他(电路板、电线、插座、木积木、砧板)。\n◆投放时，应尽量保持清洁干燥，避免污染\n◆立体包装应清空内容物，清洁后压扁投放\n◆易破损或者有裹尖锐边角的应包后投放"
        )
//        adapter.setOnLoadMoreListener(this, recycler)
        recycler.adapter = adapter
    }

    override fun loadData(_id: Int, type: Int) {
        viewModel.loadCycleWastes(_id, 1)
    }

    override fun onChanged(it: List<Waste>) {
        if (it.any()) {
            if (isFirst) {
                adapter.setNewData(it)
                isFirst = false
            } else {
                adapter.addData(it)
            }
//            adapter.loadMoreComplete()
        } else {
//            adapter.loadMoreEnd(true)
        }
    }

    override fun onDestroyView() {
        viewModel.cycleWastes.removeObserver(this)
        super.onDestroyView()
    }

    override fun onLoadMoreRequested() {
//        loadData(adapter.data[adapter.data.size - 1]._id)
    }


}
